package mianshi;

import sun.misc.Contended;

/**
 * @author MaoLin Wang
 * @description
 * @date 2020/9/1 10:58 上午
 */
public class FalseShare {

    public static void main(String[] args) throws InterruptedException {
        testFalseShare(new Pointer());
    }
    //4416
    public static void testFalseShare(Pointer pointer) throws InterruptedException {
        long start=System.currentTimeMillis();
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 1000000000; i++) {
                pointer.x.value++;
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000000000; i++) {
                pointer.y.value++;
            }
        });
        thread.start();
        thread2.start();

        thread.join();
        thread.join();

        System.out.println(System.currentTimeMillis()-start);
        System.out.println(pointer);
    }
}
class Pointer{
//    @Contended("y")需要加上jvm参数-XX:-RestrictContended
    volatile CusLong x;
    //709
    volatile CusLong y;

    public Pointer() {
        x=new CusLong();
        y=new CusLong();
    }

    @Override
    public String toString() {
        return "Pointer{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}
@Contended
class CusLong{
    long value;

    @Override
    public String toString() {
        return "CusLong{" +
                "value=" + value +
                '}';
    }
}